//
//  MapViewController.m
//  Paparazzi
//
//  Created by Eric Williams on 11/6/10.
//  Copyright 2010 Eric Williams. All rights reserved.
//

#import "MapViewController.h"
#import "FlickrFetcher.h"
#import "Photo.h"
#import "Person.h"
#import "PhotoDetailViewController.h"

@implementation MapViewController

@synthesize mapView;
@synthesize userPickerView;
@synthesize userLabel;
@synthesize userLabelBG;
@synthesize okButton;

@synthesize flickrFetcher;

@synthesize mapAnnotations;
@synthesize people;
@synthesize currentPhoto;
@synthesize currentPersonString;

+ (CGFloat)annotationPadding
{
    return 80.0f;
}

+ (CGFloat)calloutHeight
{
    return 80.0f;
}

- (void) userPickerButtonPressed
{
	self.people = [[flickrFetcher fetchManagedObjectsForEntity: @"Person" withPredicate: nil] retain];
	[self.userPickerView reloadAllComponents];
	
	// Reveal the picker
	self.userLabel.text = @"Please select a user";
	self.userPickerView.hidden = NO;
	self.userLabel.hidden = NO;
	self.userLabelBG.hidden = NO;
}

- (IBAction) userConfirmButtonPressed
{	
	// Hide the picker
	self.userPickerView.hidden = YES;
	self.okButton.hidden = YES;
	self.userLabel.hidden = YES;
	self.userLabelBG.hidden = YES;
	
	// Setup the Nav's right button to reveal a changed state in user selection
	if([self.currentPersonString length] > 12)
	{
		UIBarButtonItem *userPickerBarButtonItem = [[UIBarButtonItem alloc] initWithTitle: [self.currentPersonString substringToIndex: 12] style:UIBarButtonItemStylePlain target:self action:@selector(userPickerButtonPressed)];
		self.navigationItem.rightBarButtonItem = userPickerBarButtonItem;
		[userPickerBarButtonItem release];
	}
	else {
		UIBarButtonItem *userPickerBarButtonItem = [[UIBarButtonItem alloc] initWithTitle: self.currentPersonString style:UIBarButtonItemStylePlain target:self action:@selector(userPickerButtonPressed)];
		self.navigationItem.rightBarButtonItem = userPickerBarButtonItem;
		[userPickerBarButtonItem release];
	}
	// Let go find the annotations for this user! :)
	[self refreshAnnotations];
}

#pragma mark -
#pragma mark UIPickerViewDataSource

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return ([self.people count] + 1);		// Plus 1 for the 'ALL' option in the picker
}


#pragma mark -
#pragma mark UIPickerViewDelegate

// returns width of column and height of row for each component. 
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
	return 320.0;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
	return 40;
}

// these methods return either a plain UIString, or a view (e.g UILabel) to display the row for the component.
// for the view versions, we cache any hidden and thus unused views and pass them back for reuse. 
// If you return back a different object, the old one will be released. the view will be centered in the row rect  
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	if (row == 0)
	{
		return @"ALL";												// 'ALL' fills the 0th spot in the picker
	}
	else
	{
		return ((Person*)[self.people objectAtIndex: (row - 1)]).name;		// The object in the people array at 0 gets filled in the picker 1 and so forth
	}
}

//- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
//{
//	UIImageView *temp = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"globe.png"]];
//	return temp;
//}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	// Update the user selection
	if (row == 0) {
		self.currentPersonString = @"ALL";
		self.userLabel.text = @"Photos by everyone";
	}
	else {
		self.currentPersonString = ((Person*)[people objectAtIndex: (row - 1)]).name;
		self.userLabel.text = [NSString stringWithFormat:@"Photos by %@", self.currentPersonString];
	}
	
	// Now that someone has been selected, reveal the OK button
	self.okButton.hidden = NO;
}


#pragma mark -
#pragma mark Class


- (void) refreshAnnotations
{
	// Animate the mini nav bar retracting and then redeploying below the nav bar with the new selected user info
	// ...
	
	// Remove all the old annotations from the data and view
	for(FlickrAnnotation * oldAnnotation in self.mapAnnotations) {
		[self.mapView removeAnnotation: oldAnnotation];
	 }
	[self.mapAnnotations removeAllObjects];
	
	// TODO: Change to only needed photos (ie only for selected user(s) and only those with geo data)
	
	// Singular annotations
	FlickrAnnotation *fAnnotation1 = [[FlickrAnnotation alloc] init];
	FlickrAnnotation *fAnnotation2 = [[FlickrAnnotation alloc] init];
	
	Person * onePerson = [self.people objectAtIndex: 0];
	
	Photo * onePhoto = [[onePerson.photos allObjects] objectAtIndex:0];
	fAnnotation1.photo = onePhoto;
	NSDictionary *location1 = [flickrFetcher locationForPhotoID: onePhoto.flickrPhotoID];
	fAnnotation1.latitude = [location1 objectForKey: @"latitude"];
	fAnnotation1.longitude = [location1 objectForKey: @"longitude"];
	
	onePhoto = [[onePerson.photos allObjects] objectAtIndex:1];
	fAnnotation2.photo = onePhoto;
	NSDictionary *location2 = [flickrFetcher locationForPhotoID: onePhoto.flickrPhotoID];
	fAnnotation2.latitude = [location2 objectForKey: @"latitude"];
	fAnnotation2.longitude = [location2 objectForKey: @"longitude"];
	
	[self.mapAnnotations insertObject:fAnnotation1 atIndex:0];
	[self.mapAnnotations insertObject:fAnnotation2 atIndex: 1];
	[fAnnotation1 release];
	[fAnnotation2 release];
	
	// Display the annotation (TEMP)
	for(FlickrAnnotation * newAnnotation in self.mapAnnotations) {
		[self.mapView addAnnotation: newAnnotation];
	}
}

- (void) viewDidLoad
{
	[super viewDidLoad];
	self.navigationController.navigationBar.translucent = YES;
	self.title = @"Geo Tag Map";
	self.flickrFetcher = [[FlickrFetcher sharedInstance] retain];
	self.userLabel.text = @"Please select a user";
	self.userPickerView.showsSelectionIndicator = YES;
	
	
	// Create the annotations array
	self.mapAnnotations = [[NSMutableArray alloc] initWithCapacity:0];
	
	// Call the pick user button programmatically on first load of the view
	[self userPickerButtonPressed];
}

- (void) viewWillAppear:(BOOL)animated
{
	self.people = [[flickrFetcher fetchManagedObjectsForEntity: @"Person" withPredicate: nil] retain];
	[self.userPickerView reloadAllComponents];
}

- (void)viewDidUnload
{
	self.currentPhoto = nil;
	self.currentPersonString = nil;
    self.people = nil;
	self.mapAnnotations = nil;
	
	self.flickrFetcher = nil;
	
	self.userLabelBG = nil;
	self.userLabel = nil;
	self.userPickerView = nil;
    self.mapView = nil;
	
	self.navigationController.navigationBar.translucent = NO;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
	// Save the current photo being viewed incase of a callout selection	
	FlickrAnnotation *fAnnotation = (FlickrAnnotation*) view.annotation;
	self.currentPhoto = fAnnotation.photo;
}


- (void)showDetails:(id)sender
{
	PhotoDetailViewController * mapDetail = [[PhotoDetailViewController alloc] init];
	mapDetail.photo = currentPhoto;
	
	[self.navigationController pushViewController: mapDetail animated: YES];
}

- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    // If it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    
    // Handle our custom Flickr annotation
    if ([annotation isKindOfClass:[FlickrAnnotation class]])
    {
        // Try to dequeue an existing pin view first
        static NSString* FlickrAnnotationIdentifier = @"flickrAnnotationIdentifier";
        MKPinAnnotationView* pinView = (MKPinAnnotationView *)
		[mapView dequeueReusableAnnotationViewWithIdentifier:FlickrAnnotationIdentifier];
        if (!pinView)
        {
            // if an existing pin view was not available, create one
            MKPinAnnotationView* customPinView = [[[MKPinAnnotationView alloc]
												   initWithAnnotation:annotation reuseIdentifier:FlickrAnnotationIdentifier] autorelease];
            customPinView.pinColor = MKPinAnnotationColorRed;
            customPinView.animatesDrop = YES;
            customPinView.canShowCallout = YES;
            
            // add a detail disclosure button to the callout which will open a new view controller page
            //
            // note: you can assign a specific call out accessory view, or as MKMapViewDelegate you can implement:
            //  - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control;
            //
            
			// Setup a preview image on the left
			FlickrAnnotation *fAnnotation = (FlickrAnnotation*) annotation;
			
			NSString *photoID = fAnnotation.photo.flickrPhotoID;
			NSString *farm = fAnnotation.photo.flickrFarm;
			NSString *server = fAnnotation.photo.flickrServer;
			NSString *secret = fAnnotation.photo.flickrSecret;
			
			dispatch_queue_t flickrPreviewDownloadQueue = dispatch_queue_create("Flickr Preview Downloader", NULL);
			
			dispatch_async(flickrPreviewDownloadQueue, ^{
				NSData *currPreviewData = [self.flickrFetcher	dataForPhotoID: photoID
																fromFarm: farm
																onServer: server
																withSecret: secret
																inFormat: FlickrFetcherPhotoFormatSquare];
			
				dispatch_async(dispatch_get_main_queue(), ^{
					UIImageView *fIconView = [[UIImageView alloc] initWithImage:[UIImage imageWithData: currPreviewData]];
					fIconView.frame = CGRectMake(0, 0, 30, 30);
					fIconView.contentMode = UIViewContentModeScaleAspectFit;
					customPinView.leftCalloutAccessoryView = fIconView;
					[fIconView release];
				});
			
			});
			
			dispatch_release(flickrPreviewDownloadQueue);
						
			// Setup a button on the right to view the image full screen
			UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            [rightButton	addTarget:self
							action:@selector(showDetails:)
				  forControlEvents:UIControlEventTouchUpInside];
            customPinView.rightCalloutAccessoryView = rightButton;
			
            return customPinView;
        }
        else
        {
            pinView.annotation = annotation;
        }
        return pinView;
    }
	
	// Failure: return nil
    return nil;
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void) dealloc
{
	[people release];
	[flickrFetcher release];
	[mapAnnotations release];
	
	[userLabelBG release];
	[userLabel release];
	[userPickerView release];
	[mapView release];
	[super dealloc];
}

@end
